import { getRequest } from "./api";

// 初始化菜单
export const initMenu = (router, store) => {
    // 判断state中的routes是否有值
    if (store.state.routes.length > 0) {
        return;
    }

    // 调用后端接口获取菜单数据
    getRequest("/system/config/menu").then((data) => {
        if (data) {
            // 格式化Router
            let formRouter = formatRoutes(data);
            // 添加到路由router
            router.addRoutes(formRouter);
            // 将数据存储到Vuex中
            store.commit("initRoutes", formRouter);
        }
    });
};

export const formatRoutes = (routes) => {
    let fmtRoutes = [];

    // 遍历数组
    routes.forEach((route) => {
        // 从路由每个对象中解构出以下信息
        let { path, component, name, iconCls, children } = route;
        // 判断是否存在子类，并且子类为数组
        if (children && children instanceof Array) {
            // 递归遍历子类
            children = formatRoutes(children);
        }
        let formatRouter = {
            path: path,
            name: name,
            iconCls: iconCls,
            children: children,
            // 导入组件（类似与懒加载）
            component(resolve) {
                if (component.startsWith("Home")) {
                    require(["../views/" + component + ".vue"], resolve);
                } else if (component.startsWith("Employee")) {
                    require([
                        "../views/employee/" + component + ".vue",
                    ], resolve);
                } else if (component.startsWith("Personnel")) {
                    require([
                        "../views/personnel/" + component + ".vue",
                    ], resolve);
                } else if (component.startsWith("Salary")) {
                    require(["../views/salary/" + component + ".vue"], resolve);
                } else if (component.startsWith("Statistics")) {
                    require([
                        "../views/statistics/" + component + ".vue",
                    ], resolve);
                } else if (component.startsWith("System")) {
                    require(["../views/system/" + component + ".vue"], resolve);
                }
            },
        };
        fmtRoutes.push(formatRouter);
    });
    return fmtRoutes;
};
